package com.yusp75.myexam.com.yusp75.myexam.data

import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.sqlite.db.SimpleSQLiteQuery
import com.yusp75.myexam.data.QuestionDao
import com.yusp75.myexam.data.QuestionWithStats
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class BrowsePagingSource(
    private val questionDao: QuestionDao,
    private val query: SimpleSQLiteQuery
) : PagingSource<Int, QuestionWithStats>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, QuestionWithStats> {
        return try {
            val currentPage = params.key ?: 0
            val offset = currentPage * params.loadSize
            val modifiedQuery = buildModifiedQuery(query, params.loadSize, offset)

            val data = withContext(Dispatchers.IO) {
                questionDao.queryFilterByBuilder(modifiedQuery)
            }

            LoadResult.Page(
                data = data,
                prevKey = if (currentPage == 0) null else currentPage - 1,
                nextKey = if (data.size < params.loadSize) null else currentPage + 1
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    private fun buildModifiedQuery(
        originalQuery: SimpleSQLiteQuery,
        limit: Int,
        offset: Int
    ): SimpleSQLiteQuery {
        val sql = originalQuery.sql + " LIMIT $limit OFFSET $offset"
        return SimpleSQLiteQuery(sql)
    }

    override fun getRefreshKey(state: PagingState<Int, QuestionWithStats>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }
}
